﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.IO;
using System.Text;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using EnvironmentManagerSystem.BLL;
using EnvironmentManagerSystem.MODE;

namespace EnvironmentManagerSystem.EvaluationUnitManager
{
    public partial class EvaluationUnitEdit : System.Web.UI.Page
    {
        public int EvaluationUnitID { get; set; }

        public string QualificationFileURL
        {
            get
            {
                if (ViewState["QualificationFileURL"] == null)
                {
                    ViewState["QualificationFileURL"] = string.Empty;
                }
                return ViewState["QualificationFileURL"].ToString();
            }
            set
            {
                ViewState["QualificationFileURL"] = value;
            }
        }
        public string AllSignedURL
        {
            get
            {
                if (ViewState["AllSignedURL"] == null)
                {
                    ViewState["AllSignedURL"] = string.Empty;
                }
                return ViewState["AllSignedURL"].ToString();
            }
            set
            {
                ViewState["AllSignedURL"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (StfInfo.ReSession()) return; if (!IsPostBack)
            {
                InitUI();
                if (!(Boolean)Session["Admin"])
                {
                    txtPwd.Text = "******";
                    btnSave.Visible = false;
                    btnCancel.Visible = false;
                    btnQualificationFile.Visible = false;
                    btnAllSigned.Visible = false;
                }
            }

        }

        private void InitUI()
        {
            if (Request["ID"] != null)
            {
                EvaluationUnitID = Convert.ToInt32(Request["ID"]);
                EvaluationUnitData model = EvaluationUnit.GetModel(EvaluationUnitID);
                this.txtUnitName.Text = model.UnitName;
                this.txtAddress.Text = model.Address;
                this.txtCertificateNo.Text = model.CertificateNo;
                this.txtPhone.Text = model.Phone;
                this.txtZipCode.Text = model.ZipCode;
                this.txtEvaluationScope.Text = model.EvaluationScope;
                this.txtLoginName.Text = model.LoginName;
                this.txtPwd.Text = model.PassWord;
                //this.Image1.ImageUrl = "Image.aspx?UnitID=" + EvaluationUnitID;
                //this.Image2.ImageUrl = "Image.aspx?UnitID1=" + EvaluationUnitID;
                Image1.ImageUrl = model.QualificationFileURL;
                Image2.ImageUrl = model.AllSignedURL;
                QualificationFileURL = model.QualificationFileURL.Replace("\\", "\\\\"); ;
                AllSignedURL = model.AllSignedURL.Replace("\\", "\\\\"); ;
                BindGv();
            }
        }

        private void BindGv()
        {
            if (Request.QueryString["ID"] != null)
            {
                gvLeader.DataSource = ProjectLeader.GetList(Convert.ToInt32(Request.QueryString["ID"]));
                gvLeader.DataBind();
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (Request.QueryString["ID"] == null && EvaluationUnit.WhetherExistence(txtCertificateNo.Text.Trim()))
            {
                Jscript.Alert("证件编号已存在！", this);
                return;
            }
            if (Request.QueryString["ID"] != null && EvaluationUnit.WhetherExistence(txtCertificateNo.Text.Trim(), int.Parse(Request.QueryString["ID"])))
            {
                Jscript.Alert("证件编号已存在！", this);
                return;
            }
            UserData use = new UserData();
            use.UserName = this.txtUnitName.Text.Trim();
            use.LoginName = this.txtLoginName.Text.Trim();
            use.Password = this.txtPwd.Text.Trim();
            EvaluationUnitData model = new EvaluationUnitData();
            model.UnitName = this.txtUnitName.Text.Trim();
            model.Address = this.txtAddress.Text.Trim();
            model.CertificateNo = this.txtCertificateNo.Text.Trim();
            model.Phone = this.txtPhone.Text.Trim();
            model.ZipCode = this.txtZipCode.Text.Trim();
            model.EvaluationScope = this.txtEvaluationScope.Text.Trim();
            model.Enabled = 1;
            //model.QualificationFile = bytQualificationFile;
            //model.AllSigned = bytAllSigned;
            model.QualificationFileURL = QualificationFileURL;
            model.AllSignedURL = AllSignedURL;
            if (Request["ID"] == null)
            {
                if (EnvironmentManagerSystem.BLL.User.WhetherExistence2(use))
                {
                    Jscript.Alert("登录名已存在！", this);
                    return;
                }
                bool result = EvaluationUnit.InsertUnit(model);
                if (result == true)
                {
                    bool results = EvaluationUnit.InsertUser(model, use);
                    if (results == true)
                        Jscript.Alert("环评单位添加成功！", this);
                    else
                        Jscript.Alert("环评单位添加失败！", this);
                }
            }
            else
            {
                model.ID = Convert.ToInt32(Request.QueryString["ID"]);
                if (EnvironmentManagerSystem.BLL.User.WhetherExistence(use, model.ID))
                {
                    Jscript.Alert("登录名已存在！", this);
                    return;
                }

                bool result = EvaluationUnit.UpdateUnit(model, use);
                if (result == true)
                    Jscript.Alert("环评单位修改成功！", this);
                else
                    Jscript.Alert("环评单位修改失败！", this);
            }
        }

        protected void btnQualificationFile_Click(object sender, EventArgs e)
        {
            //bytQualificationFile = GetByte(FileUpload1, Image1);
            QualificationFileURL = GetFileUrl(FileUpload1, Image1, "QualificationFile");
        }

        protected void btnAllSigned_Click(object sender, EventArgs e)
        {
            //bytAllSigned = GetByte(FileUpload2, Image2);
            AllSignedURL = GetFileUrl(FileUpload2, Image2, "AllSigned");
        }




        private string GetFileUrl(FileUpload fuLoad, System.Web.UI.WebControls.Image img, string fileType)
        {
            string FileUrl = string.Empty;
            if (txtCertificateNo.Text.Trim() == string.Empty)
                Jscript.Alert("请先填写证件编号", this);
            else if (Request.QueryString["ID"] == null && EvaluationUnit.WhetherExistence(txtCertificateNo.Text.Trim()))
                Jscript.Alert("证件编号已存在！", this);
            else if (Request.QueryString["ID"] != null && EvaluationUnit.WhetherExistence(txtCertificateNo.Text.Trim(), int.Parse(Request.QueryString["ID"])))
                Jscript.Alert("证件编号已存在！", this);
            else
            {
                if (fuLoad.HasFile)
                {
                    bool fileOK = false;
                    string fileExtension = Path.GetExtension(fuLoad.FileName).ToLower();
                    String[] allowedExtensions = { ".gif", ".png", ".bmp", ".jpg" };
                    for (int i = 0; i < allowedExtensions.Length; i++)
                    {
                        if (fileExtension == allowedExtensions[i])
                        {
                            fileOK = true;
                        }
                    }
                    if (fileOK)
                    {
                        try
                        {
                            string Suffix = fuLoad.FileName.Split('.')[1];//获取上传文件的后缀
                            string NewName = txtCertificateNo.Text.Trim() + fileType + "." + Suffix;//重命名上传文件
                            if (!Directory.Exists(Server.MapPath(".") + "\\附件\\"))
                            {
                                Directory.CreateDirectory(Server.MapPath(".") + "\\附件\\");
                            }
                            fuLoad.PostedFile.SaveAs(Server.MapPath(".") + "\\附件\\" + NewName);
                            string upLoadPath = "附件\\" + NewName;
                            //this.Image1.ImageUrl = upLoadPath;
                            img.ImageUrl = "附件\\" + NewName;
                            FileUrl = "附件\\\\" + NewName;




                            //FileStream fstr = new FileStream(fuLoad.p, FileMode.Open);
                            //Stream fstr = fuLoad.PostedFile.InputStream;
                            //BinaryReader bin = new BinaryReader(fstr);
                            //byt = bin.ReadBytes((int)fstr.Length);
                            //fstr.Close();
                            //bin.Close();
                        }
                        catch (Exception)
                        {
                            Jscript.Alert("上传失败！", this);
                        }
                    }
                    else
                    {
                        Jscript.Alert("只能上传图片！", this);
                    }
                }
            }
            return FileUrl;
        }

        protected void gvLeader_RowEditing(object sender, GridViewEditEventArgs e)
        {
            int ID = Convert.ToInt32(gvLeader.DataKeys[e.NewEditIndex].Value);
            Response.Redirect("ProjectLeaderEdit.aspx?ID=" + ID);
        }

        protected void gvLeader_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int ID = Convert.ToInt32(gvLeader.DataKeys[e.RowIndex].Value);
            bool result = ProjectLeader.Delete(ID);
        }

        protected void btnSave0_Click(object sender, EventArgs e)
        {
            if (Request["ID"] == null)
            {
                if (Session["LeaderID"] != null)
                {
                    string LeaderID = Session["LeaderID"].ToString().TrimEnd(',');
                    gvLeader.DataSource = ProjectLeader.GetList(LeaderID);
                    gvLeader.DataBind();
                }
            }
            else
            {
                gvLeader.DataSource = ProjectLeader.GetList(Convert.ToInt32(Request.QueryString["ID"]));
                gvLeader.DataBind();
            }
        }

        #region 按钮(取消)(x)
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Write("<script>window.parent.art.dialog.list['增加评价单位'].close();</script>");
        }
        #endregion
    }
}
